

package net.qiqbframework.modelling.domain;

import net.qiqbframework.common.utils.ReflectionUtil;


import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Default implementation of {@link CreationPolicyAggregateFactory} that invokes the default, no-arguments constructor
 * of the aggregate class {@code A}.
 *
 * @param <A> The aggregate type this factory constructs.
 */
public class NoArgumentConstructorCreationPolicyAggregateFactory<A> implements CreationPolicyAggregateFactory<A> {

    private final Class<? extends A> aggregateClass;

    /**
     * Construct an instance of the {@link NoArgumentConstructorCreationPolicyAggregateFactory} for the given type.
     *
     * @param aggregateClass The aggregate type.
     */
    public NoArgumentConstructorCreationPolicyAggregateFactory(@Nonnull Class<? extends A> aggregateClass) {
        this.aggregateClass = aggregateClass;
    }

    /**
     * Creates the aggregate instance based on the previously provided type. Invokes the default, no-argument
     * constructor of the class.
     *
     * @param identifier The identifier to create the aggregate with. Not used by this factory.
     * @return An aggregate instance.
     */
    @Nonnull
    @Override
    public A create(@Nullable Object identifier) {
        try {
            return ReflectionUtil.ensureAccessible(aggregateClass.getDeclaredConstructor()).newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
